import { userName } from '@/utils/constants'

export function setCacheLong (key: string, value: string) {
  localStorage.setItem(key, value)
}

export function getCacheLong (key: string): string {
  const v = localStorage.getItem(key)
  if (v === null) {
    return ''
  }
  return v
}

export function setCacheLongWithTime (key: string, value: any) {
  const cached = {
    data: value,
    time: new Date().getTime()
  }
  localStorage.setItem(key, JSON.stringify(cached))
}

export function getCacheLongWithTime (key: string, threshold?: number): any {
  const v = localStorage.getItem(key)
  if (v === null) {
    return null
  }
  const d = JSON.parse(v)
  if (!checkExpire(d.time, threshold)) {
    return null
  }
  return d.data
}

export function getCache (key: string): string {
  const v = sessionStorage.getItem(key)
  if (v === null) {
    return ''
  }
  return v
}

export function setCache (key: string, value: string) {
  sessionStorage.setItem(key, value)
}

export function delCache (key: string) {
  sessionStorage.removeItem(key)
}

export function getUserName (): string {
  const n = getCache(userName)
  if (n.length > 0) {
    return n
  }
  const n1 = getCacheLong(userName)
  if (n1.length > 0) {
    return n1
  }
  return 'Unknown'
}

export function checkExpire (target: number, threshold?: number): boolean {
  if (threshold === undefined) {
    threshold = 24
  }
  threshold = threshold * 3600
  const cur = new Date().getTime()
  const diff = Math.round((cur - target) / 1000)
  return diff > 0 && diff < threshold
}

export function checkUserUpdateExpire (target: number): boolean {
  const diff = 24 * 3600
  const cur = new Date()
  const updateTime = new Date(cur.getFullYear(), cur.getMonth(), cur.getDate(), 3)
  const c = Math.floor(cur.getTime() / 1000)
  const u = Math.floor(updateTime.getTime() / 1000)
  const t = Math.floor(target / 1000)
  const preU = u - diff

  if (c > u) {
    return t > u
  }

  if (preU < c && c < u) {
    return preU < t && t < u
  }

  return false
}

export function getSubjectColor (subName: string): string {
  if (subName === 'CS') {
    return '3498db'
  } else if (subName === 'CCP') {
    return '9b59b6'
  } else if (subName === 'NET') {
    return 'e67e22'
  } else if (subName === 'OS') {
    return '1abc9c'
  } else if (subName === 'FUN') {
    return 'e74c3c'
  } else if (subName === 'SEQ') {
    return 'f1c40f'
  }
  return '3498db'
}

export function randInt (lowBound: number, upBound: number): number {
  const gap = upBound - lowBound
  return lowBound + Math.floor(Math.random() * gap)
}

export function getSubjectCategoryCode (subject: string): number {
  switch (subject) {
    case 'CS':
      return 1
    case 'CCP':
      return 2
    case 'OS':
      return 3
    case 'NET':
      return 4
    case 'SEQ':
      return 5
  }
  return 0
}
